package org.hard.limit.zset;

import cn.hutool.core.thread.ThreadUtil;
import com.google.common.util.concurrent.RateLimiter;

/**
 * 令牌桶学习
 * @author: 王林博
 * @date: 2023年02月27日 10:06
 */
public class LimiterTest {

    public static void main(String[] args) throws InterruptedException {
        //RateLimiter limiter = RateLimiter.create(10,2, TimeUnit.SECONDS);//QPS 100

        // 一秒钟创建10个许可证 permitsPerSecond
        RateLimiter limiter = RateLimiter.create(1);
        Thread.sleep(1000);
        long start = System.currentTimeMillis();
        for (int i= 0; i < 30; i++) {
            int finalI = i;
            ThreadUtil.execute(()->{
                limiter.acquire(); // 堵塞状态  tryAcquire 返回是否成功获取许可证
                System.out.println("执行。。" + finalI);
            });
//            double time = limiter.acquire();
//            long after = System.currentTimeMillis() - start;
//            if (time > 0D) {
//                System.out.println(i + ",limited,等待:" + time + "，已开始" + after + "毫秒");
//            } else {
//                System.out.println(i + ",enough" + "，已开始" + after + "毫秒");
//            }
            //模拟冷却时间，下一次loop可以认为是bursty开始
//            if (i == 9) {
//                Thread.sleep(2000);
//            }
                    System.out.println(Thread.currentThread().getName());
        }
//        System.out.println(Thread.currentThread().getName());
//        ThreadUtil.waitForDie(); // 为何还没结束呢，，，
        System.out.println("total time：" + (System.currentTimeMillis() - start));

    }
}
